package com.edgar.baselibrary.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;

/**
 * Created by xiexiang on 2015/10/30.
 */
public class NetworkUtils {

    public static enum NetworkStatus{
        NONE,   //未连接
        WIFI,   //wifi
        MOBILE,   //移动网络
        BLUETOOTH,  //蓝牙
        ETHERNET  //以太网
    }

    public static ConnectivityManager getConnectivityManager(Context context){
        return (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public static NetworkStatus getNetworkStatus(Context context){
        NetworkInfo networkInfo = getNetworkInfo(context);
        NetworkStatus networkStatus = NetworkStatus.NONE;
        if(networkInfo == null){
            return networkStatus;
        }
        switch (networkInfo.getType()){
            case TYPE_MOBILE:
            case TYPE_MOBILE_DUN:
            case TYPE_MOBILE_HIPRI:
            case TYPE_MOBILE_MMS:
            case TYPE_MOBILE_SUPL:
            case TYPE_WIMAX:
                networkStatus = NetworkStatus.MOBILE;
            case TYPE_WIFI:
                networkStatus = NetworkStatus.WIFI;
                break;
            case TYPE_BLUETOOTH:
                networkStatus = NetworkStatus.BLUETOOTH;
                break;
            case TYPE_ETHERNET:
                networkStatus = NetworkStatus.ETHERNET;
                break;
        }
        return networkStatus;
    }

    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager connectivityManager = getConnectivityManager(context);
        return  connectivityManager.getActiveNetworkInfo();
    }

    public static boolean isConnected(Context context){
        NetworkInfo networkInfo = getNetworkInfo(context);
        if(networkInfo == null){
            return false;
        }
        return networkInfo.isConnected();
    }
}